package club.hicode.daydayup.netty.udp.client2;

import club.hicode.daydayup.netty.udp.MessageBo;
import cn.hutool.json.JSONUtil;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.socket.DatagramPacket;
import io.netty.util.CharsetUtil;

/**
 * 客户端处理累
 *
 * @author Liu Chunfu
 * @date 2018-07-09 下午8:17
 **/
public class ClientHandler extends SimpleChannelInboundHandler<DatagramPacket> {
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, DatagramPacket packet) throws Exception {
        String body = packet.content().toString(CharsetUtil.UTF_8);
        //System.out.println("客户端收到消息:" + body);
        MessageBo messageBo = JSONUtil.toBean(body, MessageBo.class);
        String id = messageBo.getId();

        SyncFuture future = CommunicationContext.getFuture(id);
        future.setResponse(messageBo);
        CommunicationContext.clear(id);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        //super.exceptionCaught(ctx, cause);
        ctx.channel().close();
    }
}
